﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Register : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        lb_UserID.Text = setUserIDtoLabel("Cus_");
        
    }

    protected void btn_Insert_Click(object sender, EventArgs e)
    {
        UserDAO userDAO = new UserDAO();
        try
        {
            UserInfo userInfo = new UserInfo();
            userInfo.UserID = lb_UserID.Text;
            userInfo.FullName = txtFullName.Text;            
            userInfo.Address = txtAddress.Text;
            if (radMale.Checked == true)
            {
                userInfo.Gender = "Male";
            }
            else
            userInfo.Gender = "Female";
            userInfo.Phone = txtPhone.Text;
            userInfo.Email = txtEmail.Text;
            
            
            if (userDAO.Insert(userInfo) > 0)
            {

                ScriptManager.RegisterStartupScript(this, this.GetType(), "redirectMe", "alert('Insert Successfull!');", true);
                Reset();
                Response.Redirect("~/Index.aspx");
            }
            else
            {
                lblResult.Text = "Add Failed!!!";
            }

        }
        catch (Exception ex)
        {
            lblResult.Text = ex.Message;
        }
    }

    public void Reset()
    {       
        txtEmail.Text = "";
        txtFullName.Text = "";
        txtPhone.Text = "";
        radMale.Checked = true;        
        lblResult.Text = "";
    }
    protected void btn_Reset_Click(object sender, EventArgs e)
    {
        Reset();
    }
    public string setUserIDtoLabel(string typeofAccount)
    {
        UserDAO userDAO = new UserDAO();
        string temp1 = "";
        if (userDAO.GetLast_UserID(typeofAccount + "%") != null)
        {
            string userID = userDAO.GetLast_UserID(typeofAccount + "%");
            string[] temp = userID.Split('_');
            int num = int.Parse(temp[1].ToString()) + 1;
            temp1 = (num / 1000).ToString() + ((num % 1000) / 100).ToString() + (((num % 1000) % 100) / 10).ToString() + (((num % 1000) % 100) % 10).ToString();
        }
        else return typeofAccount + "0001";
        return typeofAccount + temp1;
    }
}